import json

from django.core import serializers
from django.shortcuts import render
from django.views import View
from django.http import HttpResponseRedirect, JsonResponse, HttpResponse
from django.contrib import messages
from django.db.models import Q
from .models import Menu, Commodity, CommodityDetail, CommodityImg


# Create your views here.
class CommodityView(View):
    def get(self, request, fun):
        """
        当用户发送请求时，根据用户的需求调用不同的函数
        :param request:
        :return:
        """
        if hasattr(self, fun):
            fun = getattr(self, fun)
            return fun(request)
        else:
            messages.add_message(request, messages.WARNING, '你访问的路径不存在，请确定正确的路径后重新访问')
            return HttpResponseRedirect('/')

    def search(self, request):
        """
        搜索商品，实现商品查询时优先展示包含搜索关键字商品，并同时展示关键字商品所在菜单的其他商品
        :param request:
        :return:
        """
        search = request.GET.get("q")
        commodities = Commodity.objects.filter(
            Q(title__contains=search) | Q(subtitle__contains=search) | Q(menu__name__contains=search), status=0)
        print(commodities)
        return render(request, 'search.html', {'commodities': commodities})

    def get_detail(self, request):
        """
        获取商品选项
        :param request:
        :return:
        """
        id = request.GET.get('id')  # 获取商品id
        # 通过商品id获取商品选项
        commodity = Commodity.objects.get(id=id)
        options_query = CommodityDetail.objects.filter(status=0, commodity_id=id).order_by('option_name')
        # 选项
        option_items = []
        # 价格
        price_items = []
        for i in options_query:
            option_items.append(i.option_name)
            price_items.append(i.price)
        option_items = set(option_items)
        price_items = sorted(set(price_items))
        min_price = price_items[0]
        max_price = price_items[-1]
        # 商品展示图
        commodity_show_imgs = CommodityImg.objects.filter(status=0, type=0, commodity_id=id,
                                                          commodity__status=0).order_by('-priority')
        # 商品详情图
        commodity_detail_imgs = CommodityImg.objects.filter(status=0, type=1, commodity_id=id,
                                                            commodity__status=0).order_by('-priority')
        d = {}
        for option_name in option_items:
            d[option_name] = [options_query.filter(option_name=option_name)]
        return render(request, 'detail.html',
                      {'commodity': commodity,
                       'option_query': options_query,
                       'option_item': option_items,
                       'd': d,
                       'min_price': min_price,
                       'max_price': max_price,
                       'commodity_show_imgs': commodity_show_imgs,
                       'commodity_detail_imgs': commodity_detail_imgs,
                       })

    def get_options(self, request):
        """
        获取商品选项
        :param request:
        :return:
        """
        id = request.GET.get('id')  # 获取商品id
        # 通过商品id获取商品选项
        options_query = CommodityDetail.objects.filter(status=0, commodity_id=id)
        options_list = json.loads(serializers.serialize("json", options_query, ensure_ascii=False))  # 根据结果提取构造传送数据
        data = {}
        for option in options_list:
            key = option['fields']['option_name']  # 将选项名作为构造data的key
            fields = option['fields']  # 获取选项的fields
            # 构造data
            if not data.get(key, None):  # 判断data有没有key这个字段，没有就新增
                data[key] = []
            data[key].append({
                'options': fields['options'],
                'price': fields['price'],
                'inventory': fields['inventory'],
                'img': fields['img'],
                'id': option['pk'],
            })

        # 新增
        # 实现排序：根据选项名字长度来排序，比如尺寸排在颜色分类前
        data = list(data.items())
        data.sort(key=lambda x: len(x[1]))
        dic = dict()
        dic['data'] = data
        return JsonResponse(dic)
